// 认证相关的mutations
export default {
  // 设置token
  SET_TOKEN(state, token) {
    state.token = token
    state.isAuthenticated = !!token
    
    // 将token保存到localStorage - 只在浏览器环境中执行
    if (process.client) {
      try {
        if (token) {
          localStorage.setItem('token', token)
        } else {
          localStorage.removeItem('token')
        }
      } catch (e) {
        console.error('Failed to save token to localStorage:', e)
      }
    }
  },
  
  // 设置用户信息
  SET_USER(state, user) {
    state.user = user
    
    // 更新角色和权限
    if (user) {
      state.roles = user.roles || []
      state.permissions = user.permissions || []
    } else {
      state.roles = []
      state.permissions = []
    }
    
    // 将用户信息保存到localStorage - 只在浏览器环境中执行
    if (process.client) {
      try {
        if (user) {
          localStorage.setItem('user', JSON.stringify(user))
        } else {
          localStorage.removeItem('user')
        }
      } catch (e) {
        console.error('Failed to save user to localStorage:', e)
      }
    }
  },
  
  // 设置登录加载状态
  SET_LOGIN_LOADING(state, loading) {
    state.loginLoading = loading
  },
  
  // 设置注册加载状态
  SET_REGISTER_LOADING(state, loading) {
    state.registerLoading = loading
  },
  
  // 清空认证信息
  CLEAR_AUTH(state) {
    state.token = ''
    state.user = null
    state.roles = []
    state.permissions = []
    state.isAuthenticated = false
    
    // 清空localStorage中的认证信息 - 只在浏览器环境中执行
    if (process.client) {
      try {
        localStorage.removeItem('token')
        localStorage.removeItem('user')
      } catch (e) {
        console.error('Failed to clear auth info from localStorage:', e)
      }
    }
  }
}